<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>网络网页</title>
		<style type="text/css">
			.btn {
				display: block;
				margin: 20px auto;
				padding: 5px;
				background-color: #007aff;
				border: 0;
				color: #ffffff;
				height: 40px;
				width: 200px;
			}

			.btn-red {
				background-color: #dd524d;
			}

			.btn-yellow {
				background-color: #f0ad4e;
			}

			.desc {
				padding: 10px;
				color: #999999;
			}

			.post-message-section {
				visibility: hidden;
			}
		</style>
	</head>
	<body>
		<p class="desc">web-view 组件加载网络 html 点击下列按钮，上传文件。</p>
		<input type='file' id='fileInput' />
		<div id="table">

		</div>

	</body>
	<!-- uni 的 SDK -->
	<!-- 需要把 uni.webview.1.5.6.js 下载到自己的服务器 -->
	<script type="text/javascript" src="../js/uni_sdk.js"></script>
	<!-- <script lang="javascript" src="/node_modules/xlsx/dist/xlsx.full.min.js"></script> -->
	<!-- <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script> -->
	<script lang="javascript" src="../js/xlsx.full.min.js"></script>
	<script type="text/javascript">
		document.getElementById('fileInput').addEventListener('change', function(event) {
			// 获取文件列表
			console.log("window.XLSX111111: " + JSON.stringify(window.XLSX));
			const files = event.target.files;
		
			if (files.length > 0) {
				// 处理第一个文件
				const file = files[0];
				console.log('选中的文件:', file.name);
				const reader = new FileReader();
				reader.onload = function(e) {
					// console.log('文件内容:', e.target.result);
					let start = e.target.result
					const bodyPattern = /<body[^>]*>(.*?)<\/body>/gi;
					const bodyContents = start.match(bodyPattern);
					let tableHtml = bodyPattern.exec(start)[1]
					// document.getElementById('table').innerHTML=tableHtml
					const tableData = parseTableBasic(tableHtml);
					uni.postMessage({
						data: {
							action: tableData
						}
					});
				};
				reader.readAsText(file); // 读取文件内容为文本
			}else{
					alert('导入失败了!!!')
			}
		});

		function parseTableBasic(html) {
			const rowPattern = /<tr[^>]*>(.*?)<\/tr>/gis;
			const cellPattern = /<td[^>]*>(.*?)<\/td>/gi;
			const result = [];

			let rowMatch;
			while ((rowMatch = rowPattern.exec(html)) !== null) {
				const rowHtml = rowMatch[1];
				const cells = [];
				let cellMatch;

				while ((cellMatch = cellPattern.exec(rowHtml)) !== null) {
					// 去除HTML标签，只保留文本内容
					const cellText = cellMatch[1].replace(/<[^>]+>/g, '').trim();
					cells.push(cellText);
				}

				if (cells.length > 0) {
					result.push(cells);
				}
			}

			return result;
		}
	</script>
</html>